
library(ggplot2)
library(randomForest)

inputdata<-read.csv("input_his_data.csv",header = T, check.names = F)


x<-as.data.frame(inputdata[,c(3:63)])
# 数据标准化
y <- as.factor(inputdata$histological)


# 使用randomForest函数建立随机森林模型
rf_model <- randomForest(x = x, y = y, ntree = 500)


plot(rf_model)
importance <- importance(rf_model)

rf.imp <- importance( rf_model )%>% as.data.frame ()

rf.imp %>% mutate(Variable=rownames(rf.imp))%>%
arrange(desc(MeanDecreaseAccuracy)) -> rf.imp

rf.imp$Features<-rownames(rf.imp)
#前10个特征
top_vars<- rf.imp[order(rf.imp$MeanDecreaseGini,decreasing = T),]
top_10<-top_vars[1:10,]



ggplot ( aes ( x = reorder ( Features , MeanDecreaseGini ), y = MeanDecreaseGini , fill = Features ), data = top_10 )+
  geom_col ()+
  coord_flip ()+
  theme_bw ()+
  labs ( x ="")+
  ggtitle (" Top10 variables in Randomforest ")+
  scale_fill_brewer ( palette ="Set3")+
  theme ( legend.position = "")



#提取树与 OOB 的关系的数值

err_rates<-rf_model[["err.rate"]]
err_rates%>%
as.data.frame()%>%
mutate(Tree=1:500)->err_rates
err_rates%>%
pivot_longer(cols=1:4,
names_to="OOB",
values_to="value")->err_rates
ggplot(err_rates,aes(x=Tree,y=value,color=OOB))+
geom_line(size=1)+
labs(title="The relationship between tree numberand OOB",
x="Number of Trees",y="ErrorRate")+
scale_color_brewer(palette="Set2",
name="Errorrate",
label=c("Epithelioid","Mixed","Spindle","OOB"))+
theme_bw()
